package com.bdqn.bookweb.controller;

import com.bdqn.bookweb.pojo.Books;
import com.bdqn.bookweb.pojo.Page;
import com.bdqn.bookweb.service.BooksService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BooksController {
    @Resource
    private BooksService booksService;

    @RequestMapping("/toShow")
    public String toShow(HttpSession session) {
        return "redirect:/show?currentPage=1";
    }

    @RequestMapping("/show")
    public ModelAndView show(@RequestParam int currentPage, @RequestParam(required = false) String key,@RequestParam(required = false) String value) {
        ModelAndView mav = new ModelAndView();
        String bookName = null;
        String bookAuthor = null;
        String bookPublish = null;
        if ("书名".equals(key)){
            bookName = value;
        }else if ("作者".equals(key)){
            bookAuthor = value;
        }else if ("出版社".equals(key)){
            bookPublish = value;
        }

        Page p = new Page();
        p.setPageSize(p.getPageSize());
        //添加总条数
        p.setTotalCount(booksService.selectBooks(bookName,bookAuthor,bookPublish,-1, -1).size());
        //判断最小值
        if (currentPage <= 0) {
            currentPage = 1;
        }
        //判断最大值
        if (currentPage > p.getTotalPage()) {
            currentPage = p.getTotalPage();
        }
        //添加当前页数
        p.setCurrPageNo(currentPage);
        int currentIndex = (currentPage - 1) * p.getPageSize();
        if (p.getTotalCount() == 0) {
            currentIndex = currentPage;
        }
        List<Books> books = booksService.selectBooks(bookName,bookAuthor,bookPublish,currentIndex, p.getPageSize());
        mav.addObject("totalCount", p.getTotalCount());
        mav.addObject("page", p);
        mav.addObject("books", books);
        mav.setViewName("list");
        return mav;
    }

}
